<?php
/**
 * Created by PhpStorm.
 * User: Neho
 * Date: 2018/2/24
 * Time: 13:41
 */

namespace app\admin\logic;

use think\Model;
use \think\Loader;
use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsAttributeGroup as GoodsAttributeGroupModel;
use app\common\model\GoodsAttributeKey as GoodsAttributeKeyModel;
use app\common\model\GoodsAttributeValue as GoodsAttributeValueModel;

class GoodsNature extends Model
{
    protected $goodsModel;
    protected $GoodsBrandModel;
    protected $GoodsCategoryModel;

    protected function initialize()
    {
        parent::initialize();
        $this->goodsModel = Loader::model('Goods', 'model');
        $this->goodsCategoryModel = Loader::model('GoodsCategory', 'model');
        $this->goodsBrandModel = Loader::model('GoodsBrand', 'model');
    }

    /**
     *  获取商品分类
     * @param null
     * @return array
     */
    public function category()
    {
        $list = $this->goodsCategoryModel->ls();
        $refer = array();
        $tree = array();
        foreach ($list as $k => $v) {
            $refer[$v['value']] = &$list[$k];
        }
        foreach ($list as $k => $v) {
            $parent_id = $v['parent_id'];
            if ($parent_id == 0) {
                $tree[] = &$list[$k];
            } else {
                if (isset($refer[$parent_id])) {
                    $refer[$parent_id]['children'][] = &$list[$k];
                }
            }
        }
        return $tree;
    }

    /**
     * @descrription 商品品牌
     * @param null
     * @return array
     */
    public function brand()
    {
        $list = $this->goodsBrandModel->ls();
        return $list;
    }

    /**
     *  商品属性
     * @param null
     * @return array
     */
    public function attributeGroup()
    {
        $list = GoodsAttributeGroupModel::all(function ($query) {
            $query->field('id as value, name as label');
        });
        return $list;
    }

    /**
     *  商品属性名
     * @param null
     * @return array
     */
    public function attributeKey($group)
    {
        $list = GoodsAttributeKeyModel::all(['attribute_group_id' => $group]);
        return $list;
    }

    /**
     *  商品属性值
     * @param null
     * @return array
     */
    public function attributeValue($key)
    {
        $list = GoodsAttributeValueModel::all(['attribute_key_id' => $key]);
        return $list;
    }
}